package com.earl.spider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.earl.spider.common.onlinecourse.OnlineCourseOperation;
import com.earl.spider.constants.SpiderConfig;
import com.earl.spider.entity.po.UserInfo;
import com.earl.spider.util.PropUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
public class SpiderStart {

    private static UserInfo userInfo = new UserInfo();

    static {
        try {
            String readConfig = PropUtil.readConfig(SpiderConfig.USER_INFO.getConfigKey());
            userInfo = JSON.parseObject(readConfig, UserInfo.class);
            if (StringUtils.isEmpty(userInfo)) {
                UserInfo info = new UserInfo();
                info.setBaseUrl("http://www.xdwy.com.cn/learning/");
                info.setUsername("714500200092026");
                info.setPassword("199404");
                String json = JSONObject.toJSONString(info);
                PropUtil.writeConfig(SpiderConfig.USER_INFO.getConfigKey(), json);
                throw new RuntimeException("用户配置信息为空");
            }
        } catch (Exception e) {
            log.error("读取sprider文件失败");
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        log.info("西电网课自动读取方法启动");
        int errorSum = 100;
        OnlineCourseOperation operation = null;
        for (int i = 0; i < errorSum; i++) {
            try {
                operation = new OnlineCourseOperation();
                operation.start();
                break;
            } catch (Exception e) {
                log.info("失败次数" + (i + 1));
                log.info(e.getMessage(), e);
                if (errorSum - 1 == i) {
                    throw e;
                }
            } finally {
                operation.closeBrowser();
            }
        }
        operation.closeBrowser();
        log.info("Amazon日转款下载结束");
    }
}
